package com.qf.interceptors;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Component
public class RequestHeaderInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {

        //通过线程域对象获取请求属性集对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //通过请求对象获取原始请求中的头信息
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()){
            //获取头的名字
            String headerName = headerNames.nextElement();
            //获取指定头名字的值
            String headerVal = request.getHeader(headerName);

            //通过template对象设置Feign新创建的请求对象的请求头信息
            template.header(headerName,headerVal);
        }

        //注意：实际开发，是将需要的头信息获取，并通过template对象传递到远程服务
    }
}
